from nicegui import ui
import plotly.graph_objects as go

# 全局变量存储点
points = []
fig = go.Figure()


def update_plot():
    """更新3D绘图"""
    if points:
        x, y, z = zip(*points)
        scatter = go.Scatter3d(x=x, y=y, z=z, mode='markers+text', marker=dict(size=5),
                               text=[f'Point {i + 1}' for i in range(len(points))])
    else:
        scatter = go.Scatter3d(x=[], y=[], z=[], mode='markers')

    fig.data = []
    fig.add_trace(scatter)
    ui.plotly(fig)


def add_point():
    """增加点"""
    x = float(x_input.value)
    y = float(y_input.value)
    z = float(z_input.value)
    points.append((x, y, z))
    update_plot()


def delete_point():
    """删除点"""
    if points:
        points.pop()
        update_plot()


# 创建UI
ui.label('3D Scatter Plot with NiceGUI and Plotly')

with ui.row():
    x_input = ui.input(label='X', placeholder='Enter X value')
    y_input = ui.input(label='Y', placeholder='Enter Y value')
    z_input = ui.input(label='Z', placeholder='Enter Z value')

with ui.row():
    ui.button('Add Point', on_click=add_point)
    ui.button('Delete Last Point', on_click=delete_point)

# 初始化绘图
update_plot()

# 启动NiceGUI应用
ui.run()